package controler;

import java.awt.Image;
import java.util.Collections;
import java.util.Stack;
import java.util.Vector;
import model.AbstractFactoryExpansion;
import model.ModelPlayer;
import model.ModelTile;
import modelImp.BaseExpansion;
import modelImp.Board;
import modelImp.Pawn;
import modelImp.Player;

public class InitGame {
	private static InitGame instance=null;
	
	public Board board;
	public BaseExpansion base = new BaseExpansion();
	public static Vector<AbstractFactoryExpansion> expansions = new Vector<AbstractFactoryExpansion>();
	public static Vector<ModelPlayer> players = new Vector<ModelPlayer>();

	
	
	
	// Singleton pattern
	private InitGame() throws Exception{
		Vector<ModelTile> list = base.makeTiles();
		Collections.shuffle(list);
		
		Stack<ModelTile> stack = new Stack<ModelTile>();
		for(int i=0;i<list.size();i++){
			stack.push(list.get(i));
		}
		board = new Board(base.makeFirstTile(),stack);
		
		if(players.size()<=1)
			throw new Exception("Need 2 players minimum");

	}
	
	public static void close(){
		instance = null;
		expansions = new Vector<AbstractFactoryExpansion>();
		players = new Vector<ModelPlayer>();

	}
	
	public static void addExpansions(AbstractFactoryExpansion exp) throws Exception{
		// The game isn't initialize yet, we can add expansion
		if(instance==null){
			if(expansions.contains(exp))
				throw new Exception("This expansion is already added");
			ModelTile first = exp.makeFirstTile();
			if(first!=null){
				expansions.add(exp);
			}
			else{
				for(int i=1;i<expansions.size();i++){
					if(expansions.get(i).makeFirstTile()!=null)
						throw new Exception(expansions.get(i).getNameExpansion() +" alreay use a first tile\nCannot use 2 expansions that use first tile");
				}
				expansions.add(exp);
			}
		
		}
		throw new Exception("The game is already initialize, cannot add expansion");
	}
	
	public static void addPlayer(String name,Image m) {
		Player p = new Player(name,m);
		for(int i=0;i<9;i++){
			Pawn pawn = new Pawn();
			pawn.setPlayer(p);
			p.addPawn(pawn);
		}
		players.add(p);
	}
	
	public final static InitGame getInstance() throws Exception{
		if(instance==null)
			instance = new InitGame();
		return instance;
	}
	

}
